// forked from paq's forked from: 重力マウス（ちょっぴり軽量化してみた）
// forked from fumix's 重力マウス（リンクリストにしてみた）
// forked from undo's 重力マウス
//　リンクリストにしてみたけどそんなに速くない？？
//_bmd.fillRect()を_bmd.setPixel()に変更。
//sin(),cos(),atan2(),sqrt()を排除。
package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shader;
	import flash.display.ShaderJob;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.ShaderEvent;
	import flash.geom.ColorTransform;
	import flash.text.TextField;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;

	[SWF(frameRate='60', backgroundColor='0xffffff')]
	public class ParticleTest1 extends Sprite
	{

		private static const COUNT:int = 1000000;

		private var _bitmap:BitmapData;

		[Embed('untitled.pbj', mimeType="application/octet-stream")]
		private var _bytes:Class;

		private var _colorTransform:ColorTransform;

		private var _count:uint;
		
		private var _data:Vector.<Number>;

		private var _mouse:Array = [];

		private var _shader:Shader;

		private var _skip:Array = [];
		
		private var tf:TextField;

		public function ParticleTest1()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			addEventListener(Event.ADDED_TO_STAGE, init);
			
			addChild(tf = new TextField());
		}

		private function init(evt:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);

			_colorTransform = new ColorTransform(0.9, 0.0, 0.9, 1.0);
			_bitmap = new BitmapData(465, 465, false, 0);
//			addChild(new Bitmap(_bitmap));

			_data = new Vector.<Number>(COUNT * 4);
			for (var i:int = 0; i < COUNT; i++)
			{
				_data[i * 4] = Math.random() * 465;
				_data[i * 4 + 1] = Math.random() * 465;
				_data[i * 4 + 2] = 0;
				_data[i * 4 + 3] = 0;
			}

			_shader = new Shader(new _bytes);
			_shader.data.src.input = _data;
			_shader.data.src.width = _data.length / 1000 / 4;
			_shader.data.src.height = 1000;
			_shader.data.mouse.value = _mouse;
			_shader.data.skip.value = _skip;

			addEventListener(Event.ENTER_FRAME, test);
		}

		private function test(e:Event):void
		{
			_mouse[0] = mouseX;
			_mouse[1] = mouseY;
			_skip[0] = ++_count % 4;

			var job:ShaderJob = new ShaderJob(_shader, _data, _data.length / 4 / 1000, 1000);
var t:uint = getTimer();
			job.start(true);
			tf.text = String(getTimer() - t);

			const bitmap:BitmapData = _bitmap;
			bitmap.lock();
			
			var v:Vector.<uint> = bitmap.getVector(bitmap.rect);
			for (var i:int = 0, len:uint = _data.length / 4; i < len; i++)
			{
//				v[(int(_data[i * 4]) % 465) + (int(_data[i * 4 + 1]) % 465) * 465] = 0xffffff;
			}
			bitmap.setVector(bitmap.rect, v);
			bitmap.colorTransform(_bitmap.rect, _colorTransform);
			bitmap.unlock();
		}
	}
}
